﻿
using Dapper;

using HBase;
using Net.http;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection.Emit;
using System.Reflection.Metadata;
using System.Transactions;

namespace hCommand {
    /**
   *┌────────────────────────────────────────────────┐
   *│　描    述：Component                                                    
   *│　作    者：sgj                                              
   *│　版    本：1.0                                              
   *│　创建时间：2020/9/2 11:28:16                        
   *└────────────────────────────────────────────────┘
   **/
    public class LocCoreUtil {

        static public bool UpdataWhLoc(Sw sw, long id, long goodDiff) {
            CoreWhLoc loc = sw.getById<CoreWhLoc>(id);
            if (loc != null) {//非正常货位
                if (loc.maxStock == 0) {
                    return true;
                }

                List<long> ining = inCount(sw, id);
                List<long> outing = outCount(sw, id);
                for (int i = 0; i < ining.Count; i++) {
                    if (outing.Contains(ining[i])) {
                        outing.Remove(ining[i]);
                    }
                }
                List<long> remainding = getStore(sw, id);

                int count = remainding.Count + ining.Count + outing.Count;
                if (loc.maxStock < count) {
                    ex(id, ining, outing, remainding);
                }
                if (count == 0) {
                    goodDiff = 0;
                }
                if (loc.countStock == count && loc.goodsDiff == goodDiff && loc.countIn == ining.Count && outing.Count == loc.countOut) {
                    return true;
                }

                string sql2 = @"update core_wh_loc set Count_stock=@count,goods_diff=@goodDiff,Count_out=@outing ,count_in=@ining  where id=@id";
                sw.exec(sql2, new { id, count, goodDiff, outing = outing.Count, ining = ining.Count });

                CoreWhGroup group = TransUtil.updateMoveGroup(sw, loc.areaId, loc.moveGroup, loc.craneId);
                saveCoreWhGroupStat(sw, group, loc.goodsDiff);
            } else {
                CoreWhGroup group = sw.getById<CoreWhGroup>(id);
                if (group != null) {
                    TransUtil.updateMoveGroup(sw, group.areaId, group.locGroup, 0);
                    saveCoreWhGroupStat(sw, group, goodDiff);
                }
            }
            return true;
        }

        static void ex(long id, List<long> ining, List<long> outing, List<long> remainding) {
            string e = "ining:";
            foreach (long inid in ining) {
                e += inid + ",";
            }
            e += "outing:";
            foreach (long outid in outing) {
                e += outid + ",";
            }
            e += "remainding:";
            foreach (long ramain in remainding) {
                e += ramain + ",";
            }
            throw new Exception(string.Format("[{0}]货位存放货位过多[{1}][{2}][{3}]", id, remainding.Count, ining.Count, outing.Count) + e);

        }



        static List<long> inCount(Sw sw, long stn) {
            string inCountSql = @"SELECT distinct task_Id FROM Core_task_param where des=@stn and status >= {0} and status <{1} and type = {2} ";
            inCountSql = HUtil.formatInt(inCountSql, CoreTaskParamStatus.新建, CoreTaskParamStatus.执行完成, TaskParamType.托盘搬运);
            List<long> inCount = sw.query<long>(inCountSql, new { stn }) ;
            return inCount;
        }

        static List<long> outCount(Sw sw, long stn) {
            string outCountSql = @"SELECT distinct task_Id FROM Core_task_param where src=@stn and status >= {0} and status <{1} and type = {2}";
            outCountSql = HUtil.formatInt(outCountSql, CoreTaskParamStatus.新建, CoreTaskParamStatus.执行完成, TaskParamType.托盘搬运);
            List<long> outCount = sw.query<long>(outCountSql, new { stn });
            return outCount;
        }


        static List<long> getStore(Sw sw, long stn) {
            string sql = @"select id from core_stock where  loc_Id=@locId and status in ({0},{1},{2})";//货出库中的货位，入库位置不在货位
            sql = HUtil.formatInt(sql, StockStatus.库存, StockStatus.盘库待确认, StockStatus.待盘库);
            List<long> remaindCount = sw.query<long>(sql, new { locId = stn });
            return remaindCount;
        }



        static public void saveCoreWhGroupStat(Sw sw, CoreWhGroup group, long deff) {
            if (!BaseConfig.islocGroup) {
                return;
            }
            long areaId = group.areaId;
            int groupId = group.locGroup;
            var param = new { areaId, groupId, deff };

            string sql = "select * from core_wh_group_stat where  group_Id =@groupId and  area_Id =@areaId and diff_Key=@deff ";

            CoreWhGroupStat diff = sw.queryUnique<CoreWhGroupStat>(sql, param);
            //到货位的数量
            string countSql = "SELECT sum(Count_stock) FROM core_wh_loc  where move_Group = @groupId and area_Id = @areaId and goods_Diff = @deff";
            int cont = sw.queryUnique<int>(countSql, param);
            //去区域的数量
            string iningSql = "SELECT count(*) FROM core_stock s join core_task t on s.id=t.stock_Id join core_task_param p on t.id=p.task_id " +
                " where s.deep_diff=@deff and p.des=@des and p.status >= {0} and  p.status <{1}";

            iningSql = HUtil.formatInt(iningSql, CoreTaskParamStatus.新建, CoreTaskParamStatus.执行完成);
            cont += sw.queryUnique<int>(iningSql, new { deff, des = group.id });

            if (diff == null) {
                diff = new CoreWhGroupStat();

                diff.areaId = areaId;
                diff.groupId = groupId;
                diff.diffKey = deff;
                diff.countStock = cont;
                sw.insert(diff);
            } else {
                string updateSql = "update core_wh_group_stat set count_stock=@countStock  where id=@id";
                diff.countStock = cont;
                sw.exec(updateSql, diff);
            }
        }




    }
}

